<?php
/**
 * html代码生成器
 */
namespace app\common\logic;

use app\common\model\CmsFieldModel;
use think\Request;

class CmsFieldLogic
{
    private $mid;
    private $cid;
    private $cmsMoudleCache;
    private $cmsFieldCache;
    private $cmsCategoryCache;
    private $cmsFieldModel;
    private $siteId;
    private $utype;

    public function __construct($utype, $siteId = 0)
    {
        $request                = Request::instance();
        $this->mid              = $request->param('mid/d', 0);
        $this->cid              = $request->param('cid/d', 0);
        $this->utype            = $utype;
        $this->siteId           = $siteId;
        $this->cmsMoudleCache   = cache('cms_moudle');
        $this->cmsFieldCache    = cache('cms_field' . $this->mid);
        $this->cmsCategoryCache = cache('cms_category' . $this->siteId);
        $this->cmsFieldModel    = new CmsFieldModel();
    }

    /**
     * 编辑与修改动作时根据不同字段类型获取界面
     * @return string
     */
    public function getHtml($data = [])
    {
        $field  = [];
        $layout = [];
        foreach ($this->cmsFieldCache as $k => $v) {
            if ($v['enable'] == 0) { //不处理禁用字段
                continue;
            }
            $field[]  = $v;
            $layout[] = $v['set']['layout'];
        }
        /**计算form布局 begin**/
        $layout = implode('', $layout);
        $count  = substr_count($layout, '22', 0); //计算22出现次数
        $two    = []; //双列布局出现位置
        $i      = 0;
        while ($i < $count) {
            $pos    = strpos($layout, '22');
            $layout = str_replace_limit('22', '11', $layout, 1);
            if ($pos >= 0) {
                $two[] = $pos;
                $i++;
            } else {
                break;
            }
        }
        $layoutForm = [];
        $size       = count($field);
        for ($i = 0; $i < $size; $i++) {  //重组field数量
            if (in_array($i, $two)) {
                $layoutForm[] = [$field[$i], $field[$i + 1]];
                $i += 1; //跳一级
            } else {
                $layoutForm[] = [$field[$i]];
            }
        }
        /**计算form布局 end**/
        foreach ($layoutForm as $oneKey => $one) {
            foreach ($one as $twoKey => $two) {
                $value = $this->getDefault($two['field_name'], $two['set'], $data);
                //处理函数
                if (substr($two['tips'], 0, 6) == 'widget') {
                    $h = $this->setCustomWidget($two, $value);
                } else {
                    $function = '_' . $two['field_type'];
                    $h        = $this->$function($two, $value); //当前表单
                }
                $layoutForm[$oneKey][$twoKey]['html'] = $h;
            }
        }
        return $layoutForm;
    }

    /**
     * 自定义控件处理
     * @param $field
     * @param $value
     * @return string
     */
    private function setCustomWidget($field, $value)
    {
        $widget     = explode('|', $field['tips']);
        $widgetHtml = widget($widget[1], ['field' => $field['field_name'], 'value' => $value]);
        $set        = $field['set'];
        $html       = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= $widgetHtml;
        $html .= '</div>';
        return $html;
    }

    /**
     * 获取默认值
     * @param $fieldName
     * @param $set
     * @param $data
     * @return string
     */
    private function getDefault($fieldName, $set, $data = [])
    {
        if (empty($data)) {
            if (array_key_exists('default', $set)) {
                $value = $set['default'];
            } else {
                $value = '';
            }
        } else {
            if (array_key_exists($fieldName, $data)) {
                $value = $data[$fieldName];
            } else {
                $value = '';
            }
        }
        return $value;
    }

    /**
     * 根据验证规则返回html验证字符
     * @param $validate
     * @return string
     */
    private function getValidRule($validate)
    {
        $ignore = '';
        if (empty($validate)) {
            return '';
        }
        if (!in_array('require', $validate)) { //非必填项
            $ignore = ' ignore="ignore"';
        }
        $datatypeArr = [];
        foreach ($validate as $v) {
            switch ($v) {
                case 'require':
                    $datatypeArr[] = '*';
                    break;
                case 'number':
                    $datatypeArr[] = 's';
                    break;
                case 'email':
                    $datatypeArr[] = 'e';
                    break;
                case 'url':
                    $datatypeArr[] = 'url';
                    break;
                default:
                    break;
            }
        }
        if (empty($datatypeArr)) {
            return '';
        }
        $datatype = 'datatype="' . implode(',', $datatypeArr) . '"';
        return $datatype . $ignore;
    }

    /**
     * 栏目
     * @param $field
     * @param $value
     * @return string
     */
    public function _cid($field, $value)
    {
        $set  = $field['set'];
        $html = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= "<select name=\"cid\" id=\"cid\" datatype=\"*\" class=\"form-control\">";
        $html .= "<option value=''>==选择栏目==</option>";
        //栏目必须处理到各自模型
        foreach ($this->cmsCategoryCache as $cat) {
            //排除外部链接
            if ($cat['cat_type'] == 3) {
                continue;
            }
            //非本模型栏目不显示
            if ($this->mid != $cat['mid']) {
                continue;
            }
            if ($cat['cat_type'] == 1) { //频道页不允许添加内容
                $disabled = ' disabled';
            } else {
                $disabled = '';
            }
            //当前栏目默认选中
            if ($this->cid == $cat['cid']) {
                $selected = ' selected ';
            } else {
                $selected = '';
            }
            $html .= "<option value='{$cat['cid']}' $disabled $selected>{$cat['_name']}</option>";
        }
        $html .= "</select>";
        $html .= '</div>';
        return $html;
    }

    /**
     * 属性
     * @param $field
     * @param $value
     * @return string
     */
    public function _flag($field, $value)
    {
        $set  = $field['set'];
        $flag = $this->cmsFieldModel->getFlaglist($field['mid']);
        if (!empty($value)) {
            $value = explode(',', $value);
        }
        $form = '';
        foreach ($flag as $N => $f) {
            $checked = "";
            if (!empty($value)) {
                if (in_array($f, $value)) {
                    $checked = 'checked';
                }
            }
            $form .= '<label class="checkbox-inline i-checks">
					<input type="checkbox" name="flag[]" value="' . $f . '" ' . $checked . '>
                                	' . $f . '[' . ($N + 1) . ']</label>';
        }
        $html = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= $form;
        $html .= '</div>';
        return $html;
    }

    /**
     * 模版框
     * @param $field
     * @param $value
     * @return string
     */
    public function _tpl($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        if (empty($value)) {
            $value = str_replace('cms_','','show_'.$this->cmsMoudleCache[$field['mid']]['table_name']);
        }
        $html = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<input class="form-control" type="text" placeholder="' . $field['tips'] . '"';
        $html .= 'name="' . $field['field_name'] . '" value="' . $value . '" ' . $validateRule . ' />';
        $html .= '</div>';
        return $html;
    }

    /**
     * 文本框
     * @param $field
     * @param $value
     * @return string
     */
    public function _input($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html         = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<input class="form-control" type="text" placeholder="' . $field['tips'] . '"';
        $html .= 'name="' . $field['field_name'] . '" value="' . $value . '" ' . $validateRule . ' />';
        $html .= '</div>';
        return $html;
    }

    /**
     * 数字框
     * @param $field
     * @param $value
     * @return string
     */
    public function _number($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html         = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<input class="form-control" type="text" placeholder="' . $field['tips'] . '"';
        $html .= 'name="' . $field['field_name'] . '" value="' . $value . '" ' . $validateRule . ' />';
        $html .= '</div>';
        return $html;
    }

    /**
     * 多行文本框
     * @param $field
     * @param $value
     * @return string
     */
    public function _textarea($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //验证规则
        $html         = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<textarea class="form-control" rows="3"';
        $html .= 'name="' . $field['field_name'] . '" ' . $validateRule . '>' . $value . '</textarea>';
        $html .= '</div>';
        return $html;
    }

    /**
     * 日期时间
     * @param $field
     * @param $value
     * @return string
     */
    public function _datetime($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前端不验证
        $jsFormat     = ["YYYY-MM-DD hh:mm:ss", "YYYY-MM-DD", "hh:mm:ss"];
        if ($jsFormat == 0 || $set['format'] == 2) {
            $onclick = 'onclick="laydate({istime:true,format:\'' . $jsFormat[$set['format']] . '\'});"';
        } else {
            $onclick = 'onclick="laydate();"';
        }
        $html = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<input class="form-control" type="text" placeholder="' . $field['tips'] . '" ' . $onclick;
        $html .= ' name="' . $field['field_name'] . '" value="' . $value . '" />';
        $html .= '</div>';
        return $html;
    }

    /**
     * 富文本
     * @param $field
     * @param $value
     * @return string
     */
    public function _editor($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html         = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '{:widget(\'common/Form/ueditor\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        $html .= '</div>';
        return $html;
    }

    /**
     * 选项
     * @param $field
     * @param $value
     * @return string
     */
    public function _box($field, $value)
    {
        $set = $field['set'];
        //表单值
        $_v      = explode(",", $set['options']);
        $options = [];
        foreach ($_v as $p) {
            $p              = explode("|", $p);
            $options[$p[0]] = $p[1];
        }
        $h = '';
        //select添加select
        if ($set['form_type'] == 'select') {
            $h .= "<select name=\"{$field['field_name']}\" class=\"form-control\">";
        }
        foreach ($options as $v => $text) {
            switch ($set['form_type']) {
                case "radio" :
                    $checked = $value == $v ? 'checked' : '';
                    $h .= "<label class=\"radio-inline i-checks\"><input type='radio' name=\"{$field['field_name']}\" value=\"{$v}\" {$checked}/> {$text}</label>";
                    break;
                case "checkbox" :
                    $checked = in_array($v, $value) ? 'checked=""' : '';
                    $h .= "<label class=\"checkbox-inline i-checks\"><input type='checkbox' name=\"{$field['field_name']}[]\" value=\"{$v}\" {$checked}/> {$text}</label> ";
                    break;
                case "select" :
                    $selected = $value == $v ? 'selected=""' : "";
                    $h .= "<option name=\"{$field['field_name']}\" value=\"{$v}\" {$selected}> {$text}</option>";
                    break;
            }
        }
        if ($set['form_type'] == 'select') {
            $h .= "</select>";
        }
        $html = '<label class="col-sm-2 control-label Validform_label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= $h;
        $html .= '</div>';
        return $html;
    }

    /**
     * 单图上传
     * @param $field
     * @param $value
     * @return string
     */
    public function _image($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html         = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<p class="form-control-static">';
        $html .= '{:widget(\'common/Form/singleImg\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        $html .= '</p>';
        $html .= '</div>';
        return $html;
    }

    /**
     * 多图上传
     * @param $field
     * @param $value
     */
    public function _images($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html         = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        if ($set['type'] == 'images') {
            $html .= '{:widget(\'common/Form/moreImg\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        }
        if ($set['type'] == 'imagesForm') {
            $html .= '{:widget(\'common/Form/moreTextImg\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        }
        $html .= '</div>';
        return $html;
    }

    /**
     * 单附件上传
     * @param $field
     * @param $value
     */
    public function _file($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html         = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '<p class="form-control-static">';
        $html .= '{:widget(\'common/Form/singleFile\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        $html .= '</p>';
        $html .= '</div>';
        return $html;
    }

    /**
     * 多附件上传
     * @param $field
     * @param $value
     */
    public function _files($field, $value)
    {
        $set          = $field['set'];
        $validateRule = $this->getValidRule($field['validate']); //前段不验证
        $html         = '<label class="col-sm-2 control-label">' . $field['title'] . '</label>';
        $html .= '<div class="col-sm-' . $set['size'] . '">';
        $html .= '{:widget(\'common/Form/moreFile\',[\'field\'=>\'' . $field['field_name'] . '\',\'value\'=>\'' . $value . '\',\'scene\'=>\'' . $this->utype . '\'])}';
        $html .= '</div>';
        return $html;
    }
}
